<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/4
 * Time: 16:29
 */

namespace app\common\model\app;


use app\admin\model\PageResponse;
use think\Db;
use think\Model;

class Banner extends Model
{
    protected $table = 'banner';
    protected $pk = 'id';

    private static $SaveFields = ['page','image','rank','target','link_type'];
    public static function getSaveFields(): array {
        return self::$SaveFields;
    }

    // 显示页面
    const PAGE_MAIN = 1; // 首页
    const PAGE_TEACHER = 2; // 老师（大咖）
    const PAGE_CURRICULUM = 3; // 课程
    const PAGE_PC_MAIN = 4; // PC web首页
    const PAGE_PC_ESSAY_DETAIL = 5; // PC 资讯详情
    const PAGE_PC_LIVE_QRCODE = 6; // PC 视频直播室二维码
    const PAGE_ASK_MAIN = 7; // 问答首页


    /**
     * @param int $limit
     * @param int $offset
     * @param int $page
     * @return PageResponse
     */
    public static function manageList(int $limit, int $offset, int $page = 0) {

        $filter = '';
        $params = ['limit' => $limit, 'offset' => $offset];

        if ($page > 0) {
            $filter .= ' AND page=:page ';
            $params['page'] = $page;
        }

        $sql = <<<SQL
SELECT * FROM banner
WHERE TRUE {$filter}
ORDER BY rank ASC, id DESC 
LIMIT :limit OFFSET :offset
SQL;
        $list = Db::query($sql, $params);

        $sql = <<<SQL
SELECT count(id) as num FROM banner
WHERE TRUE {$filter}
SQL;
        unset($params['limit'], $params['offset']);
        $re = Db::query($sql, $params);
        $total = $re[0]['num'] ?? 0;

        return PageResponse::success($list, $total);
    }


    public static function apiList(int $page) {

        $sql = 'select * from banner where page=:page ORDER BY rank,id';
        $banners = Db::query($sql, ['page' => $page]);

        return $banners;
    }
}